import secrets
import os
import boto3
import json
from base64 import b64encode
from hashlib import md5


def set_key(file_path):
    # # rgw_user = os.popen('radosgw-admin user list | grep testuser')
    # rgw_user = os.system('docker exec ceph-demo-0 zsh -c `radosgw-admin user list | grep testuser`')
    # if rgw_user != 0 :
    #     os.system('docker exec ceph-demo-0 zsh -c `radosgw-admin user create --uid="testuser" --display-name="First User"` > ' + file_path)
    # else:
    #     os.system('docker exec ceph-demo-0 zsh -c `radosgw-admin user info --uid="testuser"` > ' + file_path)
    with open(file_path, 'r', encoding='utf8') as fp:
        json_data = json.load(fp)
        acc = json_data['keys'][0]['access_key']
        sec = json_data['keys'][0]['secret_key']
        return acc, sec

if __name__ == '__main__':
    current_folder = os.path.dirname(os.path.abspath(__file__))
    access_key, secret_key = set_key(f'{current_folder}/secret_0.json')
    print(access_key)
    print(secret_key)

    # 定义连接到 Ceph RGW 的参数
    s3 = boto3.client(
        's3',
        endpoint_url='http://localhost:8000',
        aws_access_key_id=access_key,
        aws_secret_access_key=secret_key
    )

    # 准备加密参数
    encryption_key = secrets.token_bytes(32)
    encryption_key_b64 = b64encode(encryption_key).decode('utf-8')
    encryption_key_md5 = md5(encryption_key).digest()
    encryption_key_md5_b64 = b64encode(encryption_key_md5).decode('utf-8')

    # 将加密参数保存到文件
    with open(f'{current_folder}/encryption_key.json', 'w') as f:
        f.write(encryption_key_b64)

    # 若 bucket 不存在，则创建 bucket
    bucket_name = 'testbucket'
    all_bucket_name_list = [i['Name'] for i in s3.list_buckets()['Buckets']]
    if bucket_name not in all_bucket_name_list:
        s3.create_bucket(Bucket=bucket_name)

    # 待上传的数据：4MB 全为 'x' 的文本数据
    body = b'x' * 4 * 1024 * 1024

    # 上传数据
    response = s3.put_object(
        Bucket=bucket_name,
        Key='test_4M',
        Body=body,
        SSECustomerAlgorithm='AES256',
        SSECustomerKey=encryption_key_b64,
        SSECustomerKeyMD5=encryption_key_md5_b64
    )

    print(response)

# 9) 基于rgw s3接口上传文件，判断数据私密性保护功能
# python3 ./ceph-config/rgw_s3/put_with_crypt.py
# rados ls -p default.rgw.buckets.data
# rados get -p default.rgw.buckets.data <obj_id> test_4M
